package com.wxq.auth.controller;

import com.fasterxml.jackson.core.type.TypeReference;
import com.wxq.auth.feign.MemberFeignService;
import com.wxq.auth.utils.HttpUtils;
import com.wxq.auth.vo.WeiboUser;
import com.wxq.common.constant.AuthConstant;
import com.wxq.common.utils.JsonUtils;
import com.wxq.common.utils.R;
import com.wxq.common.vo.MemberVO;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import javax.swing.text.html.parser.Entity;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Jim
 * @date 10:45 下午 2022/4/11
 * @description 三方登陆
 * @email:huwmz04153277@126.com
 */
@Controller
public class OAuth2Controller {
    @Autowired
    private MemberFeignService memberFeignService;


    public String weibo(@RequestParam("code") String code, HttpSession session){
        Map<String, String> body = new HashMap<>();
        body.put("client_id","767355573");
        body.put("client_secret", "bb09f12990562e380984ed17844595a1");
        body.put("grant_type", "authorization_code");
        body.put("redirect_uri", "http:auth.yomall.com/oauth/weibo/success");
        body.put("code", code);
        try {
            //根据code换取access_token
            HttpResponse response = HttpUtils.doPost("https://api/weibo.com","/oauth2/access_token"
            ,"post",new HashMap<String, String>(),null,body);
            //处理响应
            if (response.getStatusLine().getStatusCode() == 200){
                //获取到access_token
                String json = EntityUtils.toString(response.getEntity());
                WeiboUser weiboUser = JsonUtils.jsonToPojo(json, WeiboUser.class);
                //登陆或者注册
                //用户第一次登陆自动注册，生成一个会员信息账号
                R r = memberFeignService.weiboLogin(weiboUser);
                MemberVO memberVO = r.getData("data", new TypeReference<MemberVO>() {});
                session.setAttribute(AuthConstant.SESSION_LOGIN_USER,memberVO);
                //登陆成功重定向到首页
                return "redirect:http://yomall.com";
            } else {
                return "redirect:http:auth.yomall.com/login.html";
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 单点登录
     * @param returnUrl
     * @param model
     * @return
     */
    @GetMapping("/login2.html")
    public  String login2Page(@RequestParam("returnUrl") String returnUrl, Model model){
        //记录登陆前页面，以便回访
        model.addAttribute("returnUrl",returnUrl);
        return "login2";
    }
}
